package com.simon.study.algorithm.thread;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 *
 * @author simon
 * @date 2022/8/28 4:21 下午
 */
public class ReentrantSpinLock {
    public AtomicInteger ai = new AtomicInteger();

    private Thread owner;
    private int count;

    public void lock(){
        if(owner == null || owner != Thread.currentThread()) {
            while (!ai.compareAndSet(0, 1)) ;
            owner = Thread.currentThread();
            count = 1;
        }else {
            count ++;
        }
    }

    public void unlock(){
        if(count == 1){
            count = 0;
            ai.compareAndSet(1, 0);
        }else {
            count--;
        }
    }


    public void olock(){
        while ( !ai.compareAndSet(0, 1) );
    }

    public void ounlock(){
        ai.compareAndSet(1, 0);
    }
}
